import time
from event_report import query_event_report
from command_issue import issue_command,query_command 


import serial


def send_at_command(port, command):
    try:
        # 打开串口
        ser = serial.Serial(f'COM{port}', baudrate=115200, timeout=1)
        print(f"成功连接到端口 {port}")
        
        # 发送AT命令
        ser.write((command + '\r\n').encode())
        print(f"已发送命令: {command}")

        time.sleep(2) 

        response = ser.read_all().decode()
        print(f"收到响应: {response}")
        
        # 检查回复是否包含'OK'
        if 'OK' in response:
            query_event_report()
        else:
            print("未收到OK响应")
        
        # 关闭串口
        ser.close()
    except serial.SerialException as e:
        print(f"连接到端口 {port} 时出错: {e}")

def listen_and_issue_command(port, command):
    try:
        # 打开串口
        ser = serial.Serial(f'COM{port}', baudrate=115200, timeout=1)
        print(f"成功连接到端口 {port} 进行监听")
        
        # 先调用issue_command方法下发指令
        issue_command()
        
        # 监听端口输出
        while True:
            response = ser.readline().decode().strip()
            if response != '':
                print(f"端口 {port} 收到输出: {response}")
            else:
                # 如果没有更多数据，等待一段时间后继续检查
                time.sleep(0.3)
    except serial.SerialException as e:
        print(f"连接到端口 {port} 时出错: {e}")

# 发送AT命令到端口3
send_at_command(3, 'AT+CTDIAGNOSE="rda_battery_low_alarm",1,30.8,85')

# 发送AT命令到端口62
# send_at_command(62, 'AT+CTDIAGNOSE="rda_battery_low_alarm",1,30.8,85')

listen_and_issue_command(3, 'AT+CTDIAGNOSE="rda_battery_low_alarm",1,30.8,85')
